﻿using MethodBoundaryAspect.Fody.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Marmat.Foundation;
using Marmat.FrameWork;

namespace Marmat.Template.WinForm
{
    /// <summary>
    ///  缓存注解。
    /// </summary>
    public class CacheAttribute : OnMethodBoundaryAspect, IProvider
    {

        public override void OnEntry(MethodExecutionArgs arg)
        {
            var key =$"{arg.Method.GetHashCode() }-{Newtonsoft.Json.JsonConvert.SerializeObject(arg.Arguments).GetHashCode()}";
            arg.MethodExecutionTag = key;
            var cache = SystemCommand.GetService<Marmat.Foundation.ICache>();
            if (cache.ContainsKey(key))
            {
                arg.ReturnValue = cache.GetValue(key);
                arg.FlowBehavior = FlowBehavior.Return;
            }
            else
                base.OnEntry(arg);
        }

        public override void OnExit(MethodExecutionArgs arg)
        {
            base.OnExit(arg);
            var cache = SystemCommand.GetService<Marmat.Foundation.ICache>();
            if (!cache.ContainsKey(arg.MethodExecutionTag))
                cache.SetValue(arg.MethodExecutionTag, arg.ReturnValue);
        }
    }
}
